package chen.huai.jie.spring.xmlconfig.mybatis;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;

import java.sql.Statement;
import java.util.*;

public class UuidGenerator extends NoKeyGenerator {
    public UuidGenerator() {
    }

    public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        Configuration configuration = ms.getConfiguration();
        Collection<Object> parameters = this.toCollection(parameter);
        Iterator var7 = parameters.iterator();

        while(var7.hasNext()) {
            Object param = var7.next();
            MetaObject metaParam = configuration.newMetaObject(param);
            String[] key = ms.getKeyProperties();
            if (metaParam.hasGetter(key[0]) && metaParam.getValue(key[0]) == null) {
                metaParam.setValue(key[0], this.uuid());
            }
        }

    }

    private String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    private Collection<Object> toCollection(Object parameter) {
        Object parameters = null;
        if (parameter instanceof Collection) {
            parameters = parameter;
        } else if (parameter instanceof Map) {
            Map parameterMap = (Map)parameter;
            if (parameterMap.containsKey("collection")) {
                parameters = parameterMap.get("collection");
            } else if (parameterMap.containsKey("list")) {
                parameters = parameterMap.get("list");
            } else if (parameterMap.containsKey("array")) {
                parameters = Arrays.asList((Object[])((Object[])parameterMap.get("array")));
            }
        }

        if (parameters == null) {
            parameters = new ArrayList();
            ((Collection)parameters).add(parameter);
        }

        return (Collection)parameters;
    }
}
